package com.bw.service.impl;

import com.bw.dao.RoleDao;
import com.bw.dao.UserDao;
import com.bw.dao.UserRoleDao;
import com.bw.dao.impl.UserRoleDaoImpl;
import com.bw.pojo.Role;
import com.bw.pojo.User;
import com.bw.pojo.UserRole;
import com.bw.pojo.vo.GetUserDetailsVo;
import com.bw.service.UserRoleService;
import com.bw.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class UserRoleServiceImpl implements UserRoleService {
    SqlSessionFactory sqlSessionFactory = MyBatisUtil.getSqlSessionFactory();
    @Override
    public List<Role> findRole(String uid) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserRoleDao userRoleMapper = sqlSession.getMapper(UserRoleDao.class);
        //1.调用dao层 查询到所有角色列表
        List<Role> list = userRoleMapper.getRoleAllList();
        //2.根据用户id查询已经拥有的橘色（中间表）
        List<UserRole> userRoles = userRoleMapper.findUserRoleByUid(uid);
        //3.合并成list一个集合
        for (Role role : list) {
            for (UserRole u : userRoles) {
                if(role.getRid().equals(u.getRid())){
                    role.setFlag(true);//如果有 设置flag 是 true
                }
            }
        }
        sqlSession.close();
        return list;
    }
    //角色
    @Override
    public List<GetUserDetailsVo> userLists() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserDao userMapper = sqlSession.getMapper(UserDao.class);
        UserRoleDao userRoleMapper = sqlSession.getMapper(UserRoleDao.class);
        //查询用户信息
        List<GetUserDetailsVo> list = userMapper.userList();
        //循环角色查看
        if(null != list && !list.isEmpty()){
            for (GetUserDetailsVo userVo : list) {
                List<Map<String,Object>> roleList =userRoleMapper.getUserRoleByUserId(userVo.getUid());
                userVo.setRoleList(roleList);
            }
        }
        sqlSession.close();
        return list;
    }

    @Override
    public void updUserRole(User user) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserRoleDao userRoleMapper = sqlSession.getMapper(UserRoleDao.class);
        userRoleMapper.getRoleAllList();
        //更新角色 1.根据用户中间表所有数据
        userRoleMapper.delUserRole(user.getUid());
        //2.根据用户id 角色id添加中间表数据
        ArrayList<Integer> arr = user.getArr();
        if(null != arr && !arr.isEmpty()){
            userRoleMapper.addUserRole(user.getUid(),arr);
        }
        sqlSession.commit();
        sqlSession.close();
    }
}
